package com.sinping.qh.api.app.version.v1.lab;

import com.sinping.qh.api.app.base.BaseAppEndPoint;
import com.sinping.qh.api.support.*;
import com.sinping.qh.dto.admin.lab.LabInspectItemRelationDto;
import com.sinping.qh.dto.admin.lab.LabInspectItemTreeDto;
import com.sinping.qh.dto.app.user.UserLaboratoryDTO;
import com.sinping.qh.dto.mongo.auth.UserSessionDTO;
import com.sinping.qh.service.admin.lab.ILabInspectItemTreeService;
import com.sinping.qh.service.app.lab.ILaboratoryByAppService;
import com.sinping.qh.utils.mapper.JsonMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author jiahuaiqing
 * @create 2018/6/9
 */
@Api(value = "app实验室和检查项", description = "app实验室和检查项API")
@RestController
@RequestMapping(value = Const.APP_URI + "/userlab", name = "app实验室和检查项")
public class LaboratoryByAppEndPoint extends BaseAppEndPoint {

    @Autowired
    ILabInspectItemTreeService iLabInspectItemTreeService;

    @Autowired
    ILaboratoryByAppService iLaboratoryByAppService;


    /**
     * 根据实验室id,获取已经配置的检查项列表
     * @return
     */
    @ApiOperation(httpMethod = "GET", value = "根据实验室id,获取已经配置的检查项列表",notes = "id是实验室id")
    @RequestMapping(value = "/configinspectitem/{id}", name = "根据实验室id,获取已经配置的检查项列表", method = RequestMethod.GET)
    public ResDto getConfigedInsepctItemByLabId(@ApiParam(name = "id", value = "xxxxxx") @PathVariable String id){
        try {
            if (!StringUtils.isNotBlank(id)) {
                return new ResDto(Const.PARAM_ERROR, "实验室id不为空");
            }
            ResDto resDto = iLaboratoryByAppService.getConfigedInsepctItemByLabId(id);
            return resDto;
        } catch (Exception e) {
            e.printStackTrace();
            return new ResDto(Const.FORMAT_ERROR, "Json数据解析异常");
        }
    }



    /**
     * 获取所有危险源隐患库列表,不分页
     *
     * @return
     */
    @ApiOperation(httpMethod = "GET", value = "获取所有危险源隐患库列表,不分页", consumes = MediaTypes.JSON)
    @RequestMapping(method = RequestMethod.GET, name = "获取所有危险源隐患库列表,不分页", value = "/alldangerlist")
    public ResDto getLabDangerList() {
        try {
            ResDto resDto = iLabInspectItemTreeService.getAllLabDangerList();
            return resDto;
        } catch (Exception e) {
            e.printStackTrace();
            return new ResDto(Const.FORMAT_ERROR, "Json数据解析异常");
        }
    }

    /**
     * 获取--实验室已经配置的检查项中的隐患描述(用在隐患记录中添加隐患描述)(包含[院系隐患或实验室隐患]+危险源隐患)
     */
    @ApiOperation(httpMethod = "GET", value = "获取实验室已经配置的检查项中的隐患描述(用在隐患记录中添加隐患描述)", consumes = MediaTypes.JSON, notes = "item_subcategory： 0 院系级;<BR>item_subcategory： 1实验室级 + lab_id")
    @RequestMapping(method = RequestMethod.GET, name = "获取实验室已经配置的检查项中的隐患描述(用在隐患记录中添加隐患描述)", value = "/labinspectitemhiddendanger")
    public ResDto getLabInspectItemDescRelation(HttpServletRequest request, @ApiParam(name = "msg", value = "{\"item_subcategory\":\"xxxxxx\",\"lab_id\":\"XXXXXXXX\"}")
    @RequestParam(required = true) String msg) {
        try {
            LabInspectItemTreeDto labInspectItemTreeDto = JsonMapper.defaultMapper().fromJson(msg, LabInspectItemTreeDto.class);
            if (labInspectItemTreeDto == null) {
                logger.error("参数为空或有不正确的数据格式");
                return new ResDto(Const.PARAM_ERROR, "参数为空或有不正确的数据格式");
            }
            if (!StringUtils.isNotBlank(labInspectItemTreeDto.getItemSubcategory())) {
                return new ResDto(Const.PARAM_ERROR, "分类不为空");
            }
            ResDto resDto = iLaboratoryByAppService.getLabInspectItemDescRelation(labInspectItemTreeDto.getItemSubcategory(), labInspectItemTreeDto.getLabId());
            return resDto;
        } catch (Exception e) {
            e.printStackTrace();
            return new ResDto(Const.FORMAT_ERROR, "Json数据解析异常");
        }
    }


    /**
     * 根据用户id,获取用户负责的院系列表[用户实验室表中的数据根据：院系进行分组]
     * "user_id":"XXXX"
     * @return
     */
    @ApiOperation(httpMethod = "GET", value = "根据用户id,获取用户负责的院系列表",notes = "user_id必传")
    @RequestMapping(value = "unitlistbyuserid", name = "根据用户id,获取用户负责的院系列表", method = RequestMethod.GET)
    public ResDto unitListByUserId(@ApiParam(name = "msg",
            value = "{\"page_size\":10, \"page_current\":1, \"order_column\":\"unit_name\", \"order_by\":\"asc\"" +
                    ", \"condition\":{\"user_id\":\"XXXX\"}}")
                                @RequestParam(required = true) String msg) {
        ResDto resDto = new ResDto(ConstEum.SUCCESS);

        FrontPage<UserLaboratoryDTO> frontPage = JsonMapper.INSTANCE.fromJson(msg, FrontPage.class);

        //查询时检查查询条件格式
        checkNull(frontPage, ConstEum.PARAM_ERROR);

        UserSessionDTO userSessionDTO = getUserSessionDto();

        //根据用户id,获取所负责的院系列表
        //frontPage = iLaboratoryByAppService.findPageByUserid(frontPage, userSessionDTO);
        frontPage = iLaboratoryByAppService.findPageByUseridAddQuanxian(frontPage, userSessionDTO);

        checkNull(frontPage, ConstEum.FAIL);

        resDto.setMsg(ConstEum.SUCCESS.getMessage());
        resDto.setDatas(JsonMapper.defaultMapper().toJson(frontPage));
        return resDto;
    }

    /**
     * 根据院系id,获取用户负责的实验室列表
     * "unit_id":"XXXX"
     * @return
     */
    @ApiOperation(httpMethod = "GET", value = "根据院系id,获取用户负责的实验室列表",notes = "manager_unit_id必传")
    @RequestMapping(value = "lablistbyunitid", name = "根据院系id,获取用户负责的实验室列表", method = RequestMethod.GET)
    public ResDto labListByUnitId(@ApiParam(name = "msg",
            value = "{\"page_size\":10, \"page_current\":1, \"order_column\":\"gmt_created\", \"order_by\":\"desc\"" +
                    ", \"condition\":{\"unit_id\":\"XXXX\"}}")
                                @RequestParam(required = true) String msg) {
        ResDto resDto = new ResDto(ConstEum.SUCCESS);

        FrontPage<UserLaboratoryDTO> frontPage = JsonMapper.INSTANCE.fromJson(msg, FrontPage.class);

        //查询时检查查询条件格式
        checkNull(frontPage, ConstEum.PARAM_ERROR);

        UserSessionDTO userSessionDTO = getUserSessionDto();

        //根据用户id,获取所负责的院系列表
        //frontPage = iLaboratoryByAppService.findPageByUnitid(frontPage, userSessionDTO);
        frontPage = iLaboratoryByAppService.findPageByUnitidAddQuanxian(frontPage, userSessionDTO);

        checkNull(frontPage, ConstEum.FAIL);

        resDto.setMsg(ConstEum.SUCCESS.getMessage());
        resDto.setDatas(JsonMapper.defaultMapper().toJson(frontPage));
        return resDto;
    }

    /**
     * 删除检查项(手机端是从已配置变未配置检查项)删除关系表中的数据
     * 取消配置
     * @param
     * @return
     */
    @ApiOperation(httpMethod = "DELETE", value = "删除检查项(取消配置)", consumes = MediaTypes.JSON,notes = "inspectItem_id:检查项id,lab_id:实验室id")
    @RequestMapping(method = RequestMethod.DELETE, name = "删除检查项", value = "/cancelinspectitem")
    public ResDto deleteLabInspectItemById(@ApiParam(name = "msg", value = "{\"inspectItem_id\":\"04769ac192e84e46ac91c473\", \"lab_id\":\"69ac192e84e46ac91\"}")
            @RequestParam(required = true) String msg) {
        LabInspectItemRelationDto labInspectItemRelationDto = JsonMapper.defaultMapper().fromJson(msg, LabInspectItemRelationDto.class);
        if (labInspectItemRelationDto == null) {
            logger.error("参数为空或有不正确的数据格式");
            return new ResDto(Const.PARAM_ERROR, "参数为空或有不正确的数据格式");
        }
        if (!StringUtils.isNotBlank(labInspectItemRelationDto.getLabId())) {
            return new ResDto(Const.PARAM_ERROR, "实验到id不为空");
        }
        if (!StringUtils.isNotBlank(labInspectItemRelationDto.getInspectItemId())) {
            return new ResDto(Const.PARAM_ERROR, "检查项id不为空");
        }
        ResDto resDto = iLaboratoryByAppService.cancleLabInspectItemById(labInspectItemRelationDto);
        return resDto;
    }


    /**
     * （配置检查项）添加--实验室配置检查项
     */
    @ApiOperation(httpMethod = "POST", value = "实验室配置检查项", consumes = MediaTypes.JSON)
    @RequestMapping(method = RequestMethod.POST, name = "实验室配置检查项", value = "/labtoinspectitem")
    public ResDto addLaboratoryInspectItemRelation(HttpServletRequest request, @ApiParam(name = "msg", value = "{\"lab_id\":\"xxxxxx\",\"inspectItem_ids\":<Br>[\"inspectItem_id\",\"inspectItem_id\"]}")
    @RequestParam(required = true) String msg) {
        try {
            LabInspectItemRelationDto labInspectItemDto = JsonMapper.defaultMapper().fromJson(msg, LabInspectItemRelationDto.class);
            if (labInspectItemDto == null) {
                logger.error("参数为空或有不正确的数据格式");
                return new ResDto(Const.PARAM_ERROR, "参数为空或有不正确的数据格式");
            }
            if (!StringUtils.isNotBlank(labInspectItemDto.getLabId())) {
                return new ResDto(Const.PARAM_ERROR, "实验室id不为空");
            }
            if (labInspectItemDto.getInspectItemIds().isEmpty()) {
                return new ResDto(Const.PARAM_ERROR, "检查项id不为空");
            }
            UserSessionDTO userSessionDto = getUserSessionDto();
            String token = userSessionDto.getToken();
            if (token.isEmpty()) {
                return new ResDto(Const.PARAM_ERROR, "token不为空");
            }
            ResDto resDto = iLabInspectItemTreeService.addLaboratoryInspectItemRelation(request, labInspectItemDto);
            return resDto;
        } catch (Exception e) {
            e.printStackTrace();
            return new ResDto(Const.FORMAT_ERROR, "Json数据解析异常");
        }
    }


}
